package ljl.codetop300;

import commons.ListNode;

public class _61_rotate_list_right {

  /**
   * 想了一下思路，然后看答案了
   * 果然我的思路不是很好
   * 就不浪费时间了
   * 我感觉用我的思路也能做，但是不浪费时间了，直接抄答案吧！
   */
  static class off {
    public ListNode rotateRight(ListNode head, int k) {
      if (k == 0 || head == null || head.next == null) {
        return head;
      }
      int n = 1;
      ListNode iter = head;
      while (iter.next != null) {
        iter = iter.next;
        n++;
      }
      /**
       * 要点：断开的位置
       * 0 1 2，k=1，从哪断开？从 1 那，怎么算？n - 1 = 2，add 不是下标，是第几个
       */
      int add = n - k % n;
      if (add == n) {
        return head;
      }
      /**
       * 要点2：连成环
       */
      iter.next = head;
      while (add-- > 0) {
        iter = iter.next;
      }
      ListNode ret = iter.next;
      iter.next = null;
      return ret;
    }
  }

  static class copy {
    public ListNode rotateRight(ListNode head, int k) {
      if (k == 0 || head == null || head.next == null) return head;
      int n = 1;
      ListNode p = head;
      while (p.next != null) {
        p = p.next;
        n++;
      }
      int breakpointPos = n - k % n;
      if (breakpointPos == n) {
        return head;
      }
      p.next = head;
      while (breakpointPos-- > 0) {
        p = p.next;
      }
      ListNode res = p.next;
      p.next = null;
      return res;
    }
  }
}
